﻿using System;
using System.Text;
using RabbitMQDemo.Common;

namespace RabbitMQDemo.Producer
{
    public class Durable
    {
        private const string ExchangeName = "durable_exchange";

        private const string QueueName = "durable_queue";

        private const string RoutingKey = "durable_routing";

        public static void Send(string[] args)
        {
            using var connection = MQClient.GetConnection();
            using var channel = connection.CreateModel();

            // 声明持久化交换机
            channel.ExchangeDeclare(exchange: ExchangeName, type: "direct", durable: true, autoDelete: false, arguments: null);

            // 声明持久化队列
            channel.QueueDeclare(queue: QueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
            channel.QueueBind(queue: QueueName, exchange: ExchangeName, routingKey: RoutingKey, arguments: null);

            // 声明持久化消息
            var properties = channel.CreateBasicProperties();
            // properties.Persistent = true;
            properties.DeliveryMode = 2;

            var index = 0;
            while (index < 10)
            {
                // 发送消息
                channel.BasicPublish(exchange: ExchangeName, routingKey: RoutingKey, mandatory: false, basicProperties: properties, body: GetMessage(index));

                // Thread.Sleep(1000);
                Console.WriteLine("Send durable message");
                index++;
            }
        }

        private static byte[] GetMessage(int? i = null) => Encoding.UTF8.GetBytes($"[Durable]{(i.HasValue ? $"[{i}]" : string.Empty)} message");
    }
}
